//导入express
const express = require('express')
const app = express()
const path = require('path')
//导入body-parser 中间件处理表单
var bodyparser = require('body-parser')

//导入cors
const cors = require('cors')
app.use(cors())

//设置为false 只能为字符串/数组 为true可为任意类型
app.use(bodyparser.urlencoded({ extended: false }))
//处理json格式的方法
app.use(bodyparser.json())


//错误处理中间件 集中错误信息返回
app.use((req, res, next) => {
    //status=0成功 =1为失败 默认设为1 ，方便处理失败的情况
    res.cc = (err, status = 1) => {
        res.send({
            status,
            //判断err
            message: err instanceof Error ? err.message : err
        })
    };
    next()
})

//引入multer 上传文件模块
const multer = require('multer');
// 定义文件存储引擎
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/upload'); // 上传文件的目标目录
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname); // 使用上传文件的原始文件名作为文件名
    }
});


//在项目文件下新建一个public 文件夹 存放文件
const upload = multer({ storage: storage });

app.use(upload.any());

//静态托管
app.use('/public', express.static(path.join(__dirname, 'public')));

//导入jwt文件
// const { authenticateToken } = require('./jwt_config/authMiddleware');
// app.use(authenticateToken);


const loginRouter = require('./route/login')
app.use('/api', loginRouter)

const userRouter = require('./route/userinfo.js')
app.use('/user', userRouter)

const usermangerRouter = require('./route/userManager')
app.use('/userManager', usermangerRouter)

const productRouter = require('./route/product.js')
app.use('/pro', productRouter)

const messageRouter = require('./route/message.js')
app.use('/msg', messageRouter)

const depMsgRouter = require('./route/department_msg.js')
app.use('/dm', depMsgRouter)

const loginLogRouter = require('./route/login_log.js')
app.use('/llog', loginLogRouter)

const operationLogRouter = require('./route/operation_log.js')
app.use('/olog', operationLogRouter)
const setRouter = require('./route/setting.js')
app.use('/set', setRouter)

const count = require('./route/count')
app.use('/count', count)

const departmentRouter = require('./route/department')
app.use('/department', departmentRouter)

//微信产品接口
const wx_product = require('./route/wx_product')
app.use('/wx_product', wx_product)


//微信产品接口
const wx_order = require('./route/order')
app.use('/wx_order', wx_order)


const wx_chat = require('./route/AIbot')
app.use('/wx_chat', wx_chat)

//对不符合验证规范进行报错
// app.use((req, res, next) => {
//     if (err instanceof Joi.validationError) return res.cc(err)
// })


// 绑定监听主机端口
app.listen(3300, () => {
    console.log('http://127.0.0.1:3300')
})